﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Windows.Forms;

namespace Client
{
    public class Connection
    {

        TcpClient connection;
        NetworkStream clientStream;
        UTF8Encoding encoder = new UTF8Encoding();
        byte[] buffer;
        byte[] message = new byte[4096];
        int bytesRead;
        Chat chat;
        Login login;

        //Private priv;
        public Connection(string _IPAddress, string _Username, Login _loginform, string _Color)
        {
            login = _loginform;

            connection = new TcpClient();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(_IPAddress), 49500);

            connection.Connect(serverEndPoint);
            connection.NoDelay = true;

            clientStream = connection.GetStream();

            buffer = encoder.GetBytes("login" + (char)2 + _Username);

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();

            message = new byte[4096];

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                string sentString = encoder.GetString(message, 0, bytesRead);
                Console.WriteLine(sentString);

                string[] splittedString = sentString.Split((char)2);

                switch (splittedString[0])
                {
                    case "acceptedlogin":
                        if (int.Parse(splittedString[1]) == 1)
                        {
                            MessageBox.Show("Login accepted. Welcome, " + _Username);
                            chat = new Chat(this,_Username, _Color);
                            //chat.listBox1_Name(_Username);
                            Thread receiverThread = new Thread(new ThreadStart(ReceiveComm));
                            receiverThread.Start();
                            //to-do: ask down roomlist and userlist from first room here
                            login.Hide();
                            chat.ShowDialog();
                            login.Show();
                            login.textBox1.Text = "";
                        }
                        else
                        {
                            MessageBox.Show("There is already a user with this " + _Username + ", please select another.");
                            return;
                        }
                        
                        break;
                }
                break;
            }
        }

        public void ReceiveComm()
        {

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    Console.WriteLine("DEBUG: Socket error. Connection terminated.");
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    Console.WriteLine("DEBUG: Client disconnectzed from the server.");
                    break;
                }

                //message has successfully been received
                string sentString = encoder.GetString(message, 0, bytesRead);

                string[] splittedString = sentString.Split((char)2);

                switch (splittedString[0])
                {
                    case "userlist":
                        this.Userlist(splittedString);
                        break;

                    case "adduser":
                        chat.listBox1_Name(splittedString[1]);
                        break;

                    case "removeuser":
                        chat.removeUser(splittedString[1]);
                        break;

                    //to-do: place all command implementations here f. e. 

                    /*case "message":
                     * call a function which writes out a message on the chat window
                     * break;
                     *
                     * etc.
                     */
                    case "message":
                        chat.message(splittedString[1]);
                        break;
                  /* case "userpriv":
                        this.UserPrivat(splittedString);
                        break;*/
                    case "roomlist":
                        this.Roomlist(splittedString);
                        break;
                    //case "roomlistUser":
                    //    this.Roomlist(splittedString);
                    //    break;
                }

            }

            this.connection.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_command"></param>
        /// <param name="_parameter"></param>
        public void sendtoServ(string _command, string _parameter)
        {
            buffer = encoder.GetBytes(_command + (char)2 + _parameter);
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="splittedString"></param>
        public void Userlist(string [] splittedString)
        {
            string[] userlist = splittedString[1].Split((char)3);
            for (int i = 0; i < userlist.Length; i++)
            {
                if (String.Compare(userlist[i], "") != 0)
                {
                    chat.listBox1_Name(userlist[i]);
                }
            }
        }

        public void Roomlist(string[] splittedString)
        {
            string[] roomlist = splittedString[1].Split((char)3);
            for (int i = 0; i < roomlist.Length; i++)
            {
                if (String.Compare(roomlist[i], "") != 0)
                {
                    chat.addroom(roomlist[i]);
                }
            }
        }
      /*  /// <summary>
        /// 
        /// </summary>
        /// <param name="splittedString"></param>
        public void UserPrivat(string [] splittedString)
        {
            for (int i = 0; i < chat.listPrivates.Count; i++)
            {
                if (String.Compare(chat.listPrivates[i].getName, splittedString[1]) == 0)
                {
                    chat.listPrivates[i].Show();
                    chat.listPrivates[i].message(splittedString[2]);
                }
            }
        }*/
    }
}